package com.zbhk.qc.service.impl;

import com.zbhk.qc.configuration.security.SecurityConfiguration;
import com.zbhk.qc.dto.*;
import com.zbhk.qc.entity.BgUser;
import com.zbhk.qc.mapper.BgUserMapper;
import com.zbhk.qc.service.BgUserService;
import com.zbhk.qc.util.MD5Util;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Lazy(false)
@Service
public class BgUserServiceImpl implements BgUserService {

    @Autowired
    private BgUserMapper BgUserMapper;


    @Override
    public BaseResponseEntity<BgLoginOutput> start(LoginInput loginInput, HttpServletRequest request) {

        BaseResponseEntity<BgLoginOutput> responseEntity = new BaseResponseEntity();
        BgLoginOutput loginOutput = new BgLoginOutput();

        Map<String,Object> map = new HashMap<>();
        map.put("code",loginInput.getAccount());
        List<BgUser> bgUserList = BgUserMapper.selectByMap(map);
        BgUser bgUser = new BgUser();
        if(null == bgUserList || bgUserList.size() == 0){
            responseEntity.setSuccess(false);
            String accessToken = "";
            loginOutput.setJwt(accessToken);
            responseEntity.setData(loginOutput);
            return responseEntity;
        }
        bgUser = bgUserList.get(0);
        if(MD5Util.createMD5(loginInput.getPassword()).equals(bgUser.getPassword())){
            responseEntity.setSuccess(true);
            String accessToken = Jwts.builder()
                    .setSubject(String.valueOf(bgUser.getCode()))
                    .setExpiration(new Date(System.currentTimeMillis() + SecurityConfiguration.ACCESS_EXPIRATION_TIME))
                    .signWith(SignatureAlgorithm.HS512, SecurityConfiguration.ACCESS_SECRET.getBytes())
                    .compact();
            loginOutput.setJwt(accessToken);
            loginOutput.setBgUser(bgUser);
            responseEntity.setData(loginOutput);
            return responseEntity;
        }else {
            responseEntity.setSuccess(false);
            String accessToken = "";
            loginOutput.setJwt(accessToken);
            responseEntity.setData(loginOutput);
            return responseEntity;
        }
    }




}

  